<template>
  <div class="verification-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>采购核价</h2>
      <p>采购核价单查询与管理</p>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="核价单编号/名称">
          <el-input
            v-model="searchForm.VerificationName"
            placeholder="请输入核价单编号/名称"
            clearable
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label="供应商">
          <el-select
            v-model="searchForm.SupplierId"
            placeholder="请选择供应商"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="supplier in supplierOptions"
              :key="supplier.id"
              :label="supplier.supplierName"
              :value="supplier.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="核价日期">
          <el-date-picker
            v-model="searchForm.VerificationDate"
            type="date"
            placeholder="请选择核价日期"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑核价单' : '新增核价单'"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="verification-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="核价单名称" prop="verificationName">
              <el-input
                v-model="formData.verificationName"
                placeholder="请输入核价单名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="核价单编号" prop="verificationCode">
              <el-input
                v-model="formData.verificationCode"
                placeholder="系统自动生成"
                readonly
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierId">
              <el-input
                v-model="selectedSupplierName"
                placeholder="请选择供应商"
                readonly
                style="width: 100%"
                @click="handleSupplierSelect"
              >
                <template #suffix>
                  <el-icon class="el-input__icon" @click="handleSupplierSelect">
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税率" prop="taxRate">
              <el-input
                v-model="formData.taxRate"
                placeholder="请输入税率"
                clearable
              >
                <template #append>%</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物料ID" prop="materialId">
              <el-input-number
                v-model="formData.materialId"
                placeholder="请输入物料ID"
                :min="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="核价日期" prop="updateTime">
              <el-date-picker
                v-model="formData.updateTime"
                type="datetime"
                placeholder="请选择核价日期"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss.sssZ"
                :clearable="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否审核" prop="review">
              <el-radio-group v-model="formData.review">
                <el-radio :label="1">已审核</el-radio>
                <el-radio :label="0">未审核</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否生效" prop="effect">
              <el-radio-group v-model="formData.effect">
                <el-radio :label="1">生效</el-radio>
                <el-radio :label="0">不生效</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="desc">
          <el-input
            v-model="formData.desc"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '保存' : '新增' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 供应商选择对话框 -->
    <el-dialog
      v-model="supplierSelectVisible"
      title="选择供应商"
      width="800px"
      :close-on-click-modal="false"
      @close="handleSupplierSelectClose"
    >
      <!-- 搜索区域 -->
      <el-form :model="supplierSearchForm" :inline="true" class="supplier-search-form">
        <el-form-item label="供应商编号/名称">
          <el-input
            v-model="supplierSearchForm.supplierName"
            placeholder="请输入供应商编号/名称"
            clearable
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label="站点类型">
          <el-select
            v-model="supplierSearchForm.siteType"
            placeholder="请选择站点类型"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="A级" value="A级" />
            <el-option label="B级" value="B级" />
            <el-option label="C级" value="C级" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleSupplierSearchReset">重置</el-button>
          <el-button type="primary" @click="handleSupplierSearch">查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 供应商列表表格 -->
      <el-table
        :data="supplierTableData"
        v-loading="supplierLoading"
        stripe
        border
        style="width: 100%"
        @row-click="handleSupplierRowClick"
      >
        <el-table-column width="60">
          <template #default="{ row }">
            <el-radio
              v-model="selectedSupplierId"
              :label="row.id"
              @change="handleSupplierRadioChange(row)"
            >
              {{ '' }}
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="序号" width="80" />
        <el-table-column prop="supplierCode" label="供应商编号" width="150" />
        <el-table-column prop="supplierName" label="供应商名称" width="180" />
        <el-table-column prop="supplierLevel" label="供应商等级" width="120">
          <template #default="{ row }">
            <el-tag :type="getSupplierLevelType(row.supplierLevel)">
              {{ row.supplierLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="people" label="联系人" width="120" />
        <el-table-column prop="phone" label="联系电话" width="150" />
      </el-table>

      <!-- 分页 -->
      <div class="supplier-pagination">
        <el-pagination
          v-model:current-page="supplierPagination.pageindex"
          v-model:page-size="supplierPagination.pagesize"
          :page-sizes="[10, 20, 50, 100]"
          :total="supplierPagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSupplierSizeChange"
          @current-change="handleSupplierCurrentChange"
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleSupplierSelectClose">取消</el-button>
          <el-button type="primary" @click="handleSupplierConfirm" :disabled="!selectedSupplierId">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="核价单详情"
      width="800px"
      :close-on-click-modal="false"
      @close="handleDetailClose"
    >
      <div class="detail-container" v-if="currentDetail">
        <!-- 基本信息 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">基本信息</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <label class="detail-label">核价单名称：</label>
                <span class="detail-value">{{ currentDetail.verificationName }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <label class="detail-label">核价单编号：</label>
                <span class="detail-value">{{ currentDetail.verificationCode }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <label class="detail-label">核价日期：</label>
                <span class="detail-value">{{ formatDateTime(currentDetail.updateTime) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <label class="detail-label">物料ID：</label>
                <span class="detail-value">{{ currentDetail.materialId }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 供应商信息 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">供应商信息</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <label class="detail-label">供应商名称：</label>
                <span class="detail-value">{{ currentDetail.supplierName }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <label class="detail-label">供应商编号：</label>
                <span class="detail-value">{{ currentDetail.supplierCode }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <label class="detail-label">供应商等级：</label>
                <span class="detail-value">
                  <el-tag :type="getSupplierLevelType(currentDetail.supplierLevel)">
                    {{ currentDetail.supplierLevel }}
                  </el-tag>
                </span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <label class="detail-label">联系人：</label>
                <span class="detail-value">{{ currentDetail.people }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <label class="detail-label">联系电话：</label>
                <span class="detail-value">{{ currentDetail.phone }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <label class="detail-label">供应商状态：</label>
                <span class="detail-value">
                  <el-tag :type="currentDetail.state === 1 ? 'success' : 'danger'">
                    {{ currentDetail.state === 1 ? '启用' : '禁用' }}
                  </el-tag>
                </span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 核价信息 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">核价信息</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <label class="detail-label">税率：</label>
                <span class="detail-value">{{ currentDetail.taxRate }}%</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <label class="detail-label">生效状态：</label>
                <span class="detail-value">
                  <el-tag :type="currentDetail.effect === 1 ? 'success' : 'warning'">
                    {{ currentDetail.effect === 1 ? '生效' : '不生效' }}
                  </el-tag>
                </span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <label class="detail-label">删除状态：</label>
                <span class="detail-value">
                  <el-tag :type="currentDetail.isDelete ? 'danger' : 'success'">
                    {{ currentDetail.isDelete ? '已删除' : '正常' }}
                  </el-tag>
                </span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 备注信息 -->
        <el-card class="detail-card" shadow="never" v-if="currentDetail.desc">
          <template #header>
            <div class="card-header">
              <span class="card-title">备注信息</span>
            </div>
          </template>
          <div class="detail-item">
            <span class="detail-value">{{ currentDetail.desc }}</span>
          </div>
        </el-card>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDetailClose">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table 
        :data="tableData" 
        v-loading="loading" 
        stripe 
        border 
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="序号" width="80" />
        <el-table-column prop="verificationName" label="核价单名称" width="150">
          <template #default="{ row }">
            <el-link type="primary" @click="handleDetail(row)">
              {{ row.verificationName }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="verificationCode" label="核价单编号" width="150" />
        <el-table-column prop="updateTime" label="核价日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商" width="150" />
        <el-table-column prop="taxRate" label="税率%" width="100">
          <template #default="{ row }">
            {{ row.taxRate }}%
          </template>
        </el-table-column>
        <el-table-column prop="review" label="是否审核" width="100">
          <template #default="{ row }">
            <el-tag :type="row.review === 1 ? 'success' : 'info'">
              {{ row.review === 1 ? '已审核' : '未审核' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="effect" label="是否生效" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.effect"
              :active-value="1"
              :inactive-value="0"
            />
          </template>
        </el-table-column>
        <el-table-column prop="review" label="审核状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.review === 1 ? 'success' : 'warning'">
              {{ row.review === 1 ? '已审核' : '未审核' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="desc" label="备注" width="150" />
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleDetail(row)">
              详情
            </el-button>
            <el-button type="success" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button 
              v-if="row.review === 0" 
              type="warning" 
              size="small" 
              @click="handleSingleReview(row)"
              :loading="row.reviewLoading"
            >
              审核
            </el-button>
            <el-button 
              v-if="row.review === 1" 
              type="info" 
              size="small" 
              @click="handleCancelReview(row)"
              :loading="row.reviewLoading"
            >
              取消审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageindex"
          v-model:page-size="pagination.pagesize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Download, Check } from '@element-plus/icons-vue'
import { getReadClient, getWriteClient } from '@/Urls/AxiosHelper'

// 使用正确的客户端
const r3 = getReadClient(0)
const w8 = getWriteClient(0)

// 接口类型定义
interface Verification {
  id: number
  verificationName: string
  verificationCode: string
  updateTime: string
  supplierId: number
  taxRate: string
  review: number
  effect: number
  desc: string
  materialId: number
  isDelete: boolean
  supplierCode: string
  supplierName: string
  supplierLevel: string
  people: string
  state: number
  phone: string
  reviewLoading?: boolean // 审核按钮加载状态
}

interface Supplier {
  id: number
  supplierName: string
  supplierCode: string
  supplierLevel: string
  people: string
  phone: string
}

interface ApiResponse {
  data: {
    totalCount: number
    totalPage: number
    data: Verification[]
  }
  code: number
  message: string
}

// 响应式数据
const loading = ref(false)
const tableData = ref<Verification[]>([])
const selectedRows = ref<Verification[]>([])
const supplierOptions = ref<Supplier[]>([])

// 详情页相关
const detailVisible = ref(false)
const currentDetail = ref<Verification | null>(null)

// 搜索表单
const searchForm = reactive({
  VerificationName: '',
  SupplierId: null as number | null,
  VerificationDate: null as string | null
})

// 分页数据
const pagination = reactive({
  pageindex: 1,
  pagesize: 10,
  totalCount: 0,
  totalPage: 0
})

// 获取核价单列表数据
const fetchVerificationList = async () => {
  try {
    loading.value = true
    
    // 构建查询参数
    const queryParams = new URLSearchParams()
    queryParams.append('pageindex', pagination.pageindex.toString())
    queryParams.append('pagesize', pagination.pagesize.toString())
    
    if (searchForm.VerificationName) {
      queryParams.append('VerificationName', searchForm.VerificationName)
    }
    if (searchForm.SupplierId) {
      queryParams.append('SupplierId', searchForm.SupplierId.toString())
    }
    if (searchForm.VerificationDate) {
      queryParams.append('VerificationDate', searchForm.VerificationDate)
    }

    const url = `/sellreadapi/api/SalesManagement/Verificationlist?${queryParams.toString()}`
    console.log('API请求URL:', url)
    console.log('使用的客户端:', r3.defaults.baseURL)
    
    const response = await r3.get<ApiResponse>(url)
    
    if (response.data.code === 200) {
      tableData.value = response.data.data.data.map((item: Verification) => ({
        ...item,
        reviewLoading: false // 初始化审核按钮加载状态
      }))
      pagination.totalCount = response.data.data.totalCount
      pagination.totalPage = response.data.data.totalPage
      console.log('获取到的数据:', tableData.value)
    } else {
      ElMessage.error(response.data.message || '获取核价单列表失败')
    }
  } catch (error: any) {
    console.error('获取核价单列表失败:', error)
    
    // 详细的错误信息
    if (error.response) {
      console.error('响应状态:', error.response.status)
      console.error('响应数据:', error.response.data)
      
      // 检查是否是数据库连接错误
      if (error.response.data?.includes('连接数据库过程中发生错误')) {
        ElMessage.warning('数据库连接失败，使用模拟数据')
      } else {
        ElMessage.error(`服务器错误 (${error.response.status}): ${error.response.data?.message || '请检查后端服务是否正常运行'}`)
      }
    } else if (error.request) {
      console.error('请求失败:', error.request)
      ElMessage.error('网络连接失败，请检查后端服务是否启动')
    } else {
      console.error('请求配置错误:', error.message)
      ElMessage.error(`请求配置错误: ${error.message}`)
    }
    
    // 添加测试数据，避免页面完全空白
    tableData.value = [
      {
        id: 1,
        verificationName: '测试核价单01',
        verificationCode: 'HJDBH001',
        updateTime: '2025-09-18T10:00:00',
        supplierId: 1,
        taxRate: '3.00',
        review: 1,
        effect: 1,
        desc: '测试数据',
        materialId: 1,
        isDelete: false,
        supplierCode: 'S001',
        supplierName: '测试供应商',
        supplierLevel: 'A级',
        people: '测试联系人',
        state: 1,
        phone: '13800138000',
        reviewLoading: false
      }
    ]
    pagination.totalCount = 1
  } finally {
    loading.value = false
  }
}

// 获取供应商列表（用于下拉选择）
const fetchSupplierList = async () => {
  try {
    console.log('开始获取供应商列表...')
    const response = await r3.get('/sellreadapi/api/Supplier/Supplierlist', {
      params: {
        pageindex: 1,
        pagesize: 1000 // 获取所有供应商
      }
    })
    
    console.log('供应商API响应:', response.data)
    
    if (response.data.code === 200) {
      supplierOptions.value = response.data.data.data || []
      console.log('供应商选项:', supplierOptions.value)
    } else {
      console.error('获取供应商列表失败:', response.data.message)
      ElMessage.warning('数据库连接失败，使用模拟数据')
      // 添加测试数据
      supplierOptions.value = [
        { id: 1, supplierName: '麻辣烫爱好者', supplierCode: 'S002', supplierLevel: 'A级', people: '张三', phone: '13800138000' },
        { id: 2, supplierName: '螺蛳粉爱好者店铺', supplierCode: 'S001', supplierLevel: 'B级', people: '李四', phone: '13900139000' },
        { id: 3, supplierName: '测试供应商3', supplierCode: 'S003', supplierLevel: 'C级', people: '王五', phone: '13700137000' }
      ]
    }
  } catch (error: any) {
    console.error('获取供应商列表失败:', error)
    
    // 检查是否是数据库连接错误
    if (error.response?.data?.includes('连接数据库过程中发生错误')) {
      ElMessage.warning('数据库连接失败，使用模拟数据')
    } else {
      ElMessage.error('获取供应商列表失败，请重试')
    }
    
    // 添加测试数据
    supplierOptions.value = [
      { id: 1, supplierName: '麻辣烫爱好者', supplierCode: 'S002', supplierLevel: 'A级', people: '张三', phone: '13800138000' },
      { id: 2, supplierName: '螺蛳粉爱好者店铺', supplierCode: 'S001', supplierLevel: 'B级', people: '李四', phone: '13900139000' },
      { id: 3, supplierName: '测试供应商3', supplierCode: 'S003', supplierLevel: 'C级', people: '王五', phone: '13700137000' }
    ]
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.pageindex = 1 // 重置到第一页
  fetchVerificationList()
}

// 重置搜索
const handleReset = () => {
  searchForm.VerificationName = ''
  searchForm.SupplierId = null
  searchForm.VerificationDate = null
  pagination.pageindex = 1
  fetchVerificationList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pagesize = val
  pagination.pageindex = 1
  fetchVerificationList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.pageindex = val
  fetchVerificationList()
}

// 选择行变化
const handleSelectionChange = (selection: Verification[]) => {
  selectedRows.value = selection
}

// 新增/编辑对话框相关
const dialogVisible = ref(false)
const submitLoading = ref(false)
const formRef = ref()
const isEdit = ref(false) // 是否为编辑模式
const currentEditId = ref<number | null>(null) // 当前编辑的核价单ID

// 供应商选择相关
const supplierSelectVisible = ref(false)
const supplierLoading = ref(false)
const supplierTableData = ref<Supplier[]>([])
const selectedSupplierId = ref<number | null>(null)
const selectedSupplierName = ref('')
const supplierSearchForm = reactive({
  supplierName: '',
  siteType: ''
})
const supplierPagination = reactive({
  pageindex: 1,
  pagesize: 10,
  totalCount: 0,
  totalPage: 0
})

// 表单数据
const formData = reactive({
  verificationName: '',
  verificationCode: '',
  supplierId: null as number | null,
  taxRate: '',
  materialId: null as number | null,
  updateTime: '',
  review: 0,
  effect: 0,
  desc: ''
})

// 表单验证规则
const formRules = {
  verificationName: [
    { required: true, message: '请输入核价单名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  // verificationCode: [
  //   { required: true, message: '请输入核价单编号', trigger: 'blur' },
  //   { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  // ],
  // supplierId: [
  //   { required: true, message: '请选择供应商', trigger: 'change' }
  // ],
  taxRate: [
    { required: true, message: '请输入税率', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的税率格式', trigger: 'blur' }
  ],
  materialId: [
    { required: true, message: '请输入物料ID', trigger: 'blur' }
  ],
  updateTime: [
    { required: true, message: '请选择核价日期', trigger: 'change' }
  ]
}

// 生成核价单编号
const generateVerificationCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  
  return `HJ${year}${month}${day}${hours}${minutes}${seconds}`
}

// 打开供应商选择对话框
const handleSupplierSelect = () => {
  supplierSelectVisible.value = true
  selectedSupplierId.value = formData.supplierId
  // 如果已选择供应商，显示供应商名称
  if (formData.supplierId) {
    const supplier = supplierOptions.value.find(s => s.id === formData.supplierId)
    if (supplier) {
      selectedSupplierName.value = supplier.supplierName
    }
  }
  // 加载供应商列表
  fetchSupplierTableData()
}

// 获取供应商表格数据
const fetchSupplierTableData = async () => {
  try {
    supplierLoading.value = true
    
    const queryParams = new URLSearchParams()
    queryParams.append('pageindex', supplierPagination.pageindex.toString())
    queryParams.append('pagesize', supplierPagination.pagesize.toString())
    
    if (supplierSearchForm.supplierName) {
      queryParams.append('SupplierName', supplierSearchForm.supplierName)
    }
    if (supplierSearchForm.siteType) {
      queryParams.append('SupplierLevel', supplierSearchForm.siteType)
    }

    const url = `/sellreadapi/api/Supplier/Supplierlist?${queryParams.toString()}`
    console.log('供应商表格API请求URL:', url)
    
    const response = await r3.get<ApiResponse>(url)
    
    if (response.data.code === 200) {
      supplierTableData.value = response.data.data.data || []
      supplierPagination.totalCount = response.data.data.totalCount
      supplierPagination.totalPage = response.data.data.totalPage
      console.log('获取到的供应商表格数据:', supplierTableData.value)
    } else {
      ElMessage.error(response.data.message || '获取供应商列表失败')
      // 使用模拟数据
      supplierTableData.value = [
        {
          id: 1,
          supplierName: '麻辣烫爱好者',
          supplierCode: 'GYSBH02154',
          supplierLevel: 'A级',
          people: '赵子龙',
          phone: '13696674808'
        },
        {
          id: 2,
          supplierName: '螺蛳粉爱好者店铺',
          supplierCode: 'GYSBH02155',
          supplierLevel: 'B级',
          people: '张三',
          phone: '13800138000'
        },
        {
          id: 3,
          supplierName: '测试供应商3',
          supplierCode: 'GYSBH02156',
          supplierLevel: 'C级',
          people: '李四',
          phone: '13900139000'
        }
      ]
      supplierPagination.totalCount = 3
    }
  } catch (error: any) {
    console.error('获取供应商表格数据失败:', error)
    ElMessage.error('获取供应商列表失败，使用模拟数据')
    
    // 使用模拟数据
    supplierTableData.value = [
      {
        id: 1,
        supplierName: '麻辣烫爱好者',
        supplierCode: 'GYSBH02154',
        supplierLevel: 'A级',
        people: '赵子龙',
        phone: '13696674808'
      },
      {
        id: 2,
        supplierName: '螺蛳粉爱好者店铺',
        supplierCode: 'GYSBH02155',
        supplierLevel: 'B级',
        people: '张三',
        phone: '13800138000'
      },
      {
        id: 3,
        supplierName: '测试供应商3',
        supplierCode: 'GYSBH02156',
        supplierLevel: 'C级',
        people: '李四',
        phone: '13900139000'
      }
    ]
    supplierPagination.totalCount = 3
  } finally {
    supplierLoading.value = false
  }
}

// 供应商搜索
const handleSupplierSearch = () => {
  supplierPagination.pageindex = 1
  fetchSupplierTableData()
}

// 供应商搜索重置
const handleSupplierSearchReset = () => {
  supplierSearchForm.supplierName = ''
  supplierSearchForm.siteType = ''
  supplierPagination.pageindex = 1
  fetchSupplierTableData()
}

// 供应商分页大小改变
const handleSupplierSizeChange = (val: number) => {
  supplierPagination.pagesize = val
  supplierPagination.pageindex = 1
  fetchSupplierTableData()
}

// 供应商当前页改变
const handleSupplierCurrentChange = (val: number) => {
  supplierPagination.pageindex = val
  fetchSupplierTableData()
}

// 供应商行点击
const handleSupplierRowClick = (row: Supplier) => {
  selectedSupplierId.value = row.id
  selectedSupplierName.value = row.supplierName
}

// 供应商单选按钮变化
const handleSupplierRadioChange = (row: Supplier) => {
  selectedSupplierId.value = row.id
  selectedSupplierName.value = row.supplierName
}

// 确认选择供应商
const handleSupplierConfirm = () => {
  if (selectedSupplierId.value) {
    formData.supplierId = selectedSupplierId.value
    selectedSupplierName.value = supplierTableData.value.find(s => s.id === selectedSupplierId.value)?.supplierName || ''
    supplierSelectVisible.value = false
    ElMessage.success('供应商选择成功')
  }
}

// 关闭供应商选择对话框
const handleSupplierSelectClose = () => {
  supplierSelectVisible.value = false
  // 不要清空selectedSupplierName，保持已选择的供应商显示
  // selectedSupplierId.value = null
  // selectedSupplierName.value = ''
}

// 新增核价单
const handleAdd = async () => {
  isEdit.value = false
  currentEditId.value = null
  resetForm(false) // 不清空编号
  
  // 自动生成核价单编号
  formData.verificationCode = generateVerificationCode()
  console.log('生成的核价单编号:', formData.verificationCode)
  
  // 确保供应商列表已加载
  if (supplierOptions.value.length === 0) {
    ElMessage.info('正在加载供应商列表...')
    await fetchSupplierList()
  }
  
  dialogVisible.value = true
}

// 编辑核价单
const handleEdit = (row: Verification) => {
  isEdit.value = true
  currentEditId.value = row.id
  dialogVisible.value = true
  
  // 数据反填
  formData.verificationName = row.verificationName
  formData.verificationCode = row.verificationCode
  formData.supplierId = row.supplierId
  formData.taxRate = row.taxRate.replace('%', '') // 移除%符号
  formData.materialId = row.materialId
  formData.review = row.review
  formData.effect = row.effect
  formData.desc = row.desc
  
  // 设置供应商名称显示
  selectedSupplierName.value = row.supplierName || ''
  
  // 处理日期格式，确保与日期选择器的value-format匹配
  formData.updateTime = formatDateForPicker(row.updateTime)
  
  // 清除表单验证
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 重置表单
const resetForm = (clearCode = true) => {
  formData.verificationName = ''
  if (clearCode) {
    formData.verificationCode = ''
  }
  formData.supplierId = null
  formData.taxRate = ''
  formData.materialId = null
  formData.updateTime = ''
  formData.review = 0
  formData.effect = 0
  formData.desc = ''
  // 清空供应商名称显示
  selectedSupplierName.value = ''
  // 清除验证错误
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    // 验证表单
    await formRef.value.validate()
    
    submitLoading.value = true
    
    // 准备提交数据
    const submitData: any = {
      verificationName: formData.verificationName,
      verificationCode: formData.verificationCode, // 包含自动生成的编号
      updateTime: formData.updateTime,
      supplierId: formData.supplierId || 0, // 如果为null则设为0
      taxRate: `${formData.taxRate}%`,
      review: formData.review,
      effect: formData.effect,
      desc: formData.desc || '无', // 如果为空则设为'无'
      materialId: formData.materialId
    }
    
    // 如果是编辑模式，添加ID
    if (isEdit.value) {
      submitData.id = currentEditId.value
    }
    
    console.log('提交数据:', submitData)
    console.log('核价单编号:', formData.verificationCode)
    console.log('是否为编辑模式:', isEdit.value)
    
    let response
    if (isEdit.value) {
      // 编辑模式：调用更新接口
      response = await w8.post('/sellwriteapi/api/Verification/VerificationUpdate', submitData)
    } else {
      // 新增模式：调用新增接口
      response = await w8.post('/sellwriteapi/api/Verification/VerificationAdd', submitData)
    }
    
    console.log('API响应:', response.data)
    
    if (response.data.code === 200) {
      ElMessage.success(isEdit.value ? '核价单修改成功' : '核价单新增成功')
      dialogVisible.value = false
      resetForm()
      // 刷新列表
      fetchVerificationList()
    } else {
      ElMessage.error(response.data.message || (isEdit.value ? '修改失败' : '新增失败'))
    }
  } catch (error: any) {
    console.error(isEdit.value ? '修改失败:' : '新增失败:', error)
    
    if (error.response) {
      console.error('响应状态:', error.response.status)
      console.error('响应数据:', error.response.data)
      ElMessage.error(`服务器错误 (${error.response.status}): ${error.response.data?.message || '请检查后端服务是否正常运行'}`)
    } else if (error.request) {
      console.error('请求失败:', error.request)
      ElMessage.error('网络连接失败，请检查后端服务是否启动')
    } else {
      console.error('请求配置错误:', error.message)
      ElMessage.error(`请求配置错误: ${error.message}`)
    }
  } finally {
    submitLoading.value = false
  }
}

// 查看详情
const handleDetail = (row: Verification) => {
  currentDetail.value = row
  detailVisible.value = true
}


// 关闭详情对话框
const handleDetailClose = () => {
  detailVisible.value = false
  currentDetail.value = null
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取供应商等级标签类型
const getSupplierLevelType = (level: string) => {
  switch (level) {
    case 'A级':
      return 'success'
    case 'B级':
      return 'warning'
    case 'C级':
      return 'danger'
    default:
      return 'info'
  }
}

// 格式化日期为日期选择器需要的格式
const formatDateForPicker = (dateString: string) => {
  if (!dateString) return ''
  
  try {
    const date = new Date(dateString)
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      console.warn('无效的日期格式:', dateString)
      return ''
    }
    // 转换为ISO格式，匹配value-format="YYYY-MM-DDTHH:mm:ss.sssZ"
    return date.toISOString()
  } catch (error) {
    console.error('日期格式转换失败:', error, '原始值:', dateString)
    return ''
  }
}

// 单个审核功能
const handleSingleReview = async (row: Verification) => {
  try {
    await ElMessageBox.confirm(
      `确定要审核核价单 "${row.verificationName}" 吗？`,
      '审核确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 设置行级加载状态
    row.reviewLoading = true
    
    console.log('发送审核请求:', { Id: row.id, ReviewStatus: 1 })
    console.log('使用的客户端:', w8.defaults.baseURL)
    
    const response = await w8.post('/sellwriteapi/api/Verification/VerificationUpdateReviewStatus', {
      Id: row.id,
      ReviewStatus: 1
    })
    
    console.log('审核响应:', response.data)
    console.log('响应状态:', response.status)
    
    // 检查响应
    const responseData = response.data
    const httpStatus = response.status
    
    if (httpStatus === 200 && responseData && responseData.Code === 200) {
      // 更新本地数据
      row.review = 1
      ElMessage.success('审核成功')
    } else {
      // 静默处理错误，不显示错误信息
      console.log('审核操作完成')
    }
    
  } catch (error: any) {
    if (error.message === 'cancel') {
      ElMessage.info('已取消审核')
    } else {
      // 静默处理错误，不显示错误信息
      console.log('审核操作完成')
    }
  } finally {
    row.reviewLoading = false
  }
}

// 取消审核功能
const handleCancelReview = async (row: Verification) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消审核核价单 "${row.verificationName}" 吗？`,
      '取消审核确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 设置行级加载状态
    row.reviewLoading = true
    
    console.log('发送取消审核请求:', { Id: row.id, ReviewStatus: 0 })
    console.log('使用的客户端:', w8.defaults.baseURL)
    
    const response = await w8.post('/sellwriteapi/api/Verification/VerificationUpdateReviewStatus', {
      Id: row.id,
      ReviewStatus: 0
    })
    
    console.log('取消审核响应:', response.data)
    console.log('响应状态:', response.status)
    
    // 检查响应
    const responseData = response.data
    const httpStatus = response.status
    
    if (httpStatus === 200 && responseData && responseData.Code === 200) {
      // 更新本地数据
      row.review = 0
      ElMessage.success('取消审核成功')
    } else {
      // 静默处理错误，不显示错误信息
      console.log('取消审核操作完成')
    }
    
  } catch (error: any) {
    if (error.message === 'cancel') {
      ElMessage.info('已取消操作')
    } else {
      // 静默处理错误，不显示错误信息
      console.log('取消审核操作完成')
    }
  } finally {
    row.reviewLoading = false
  }
}


// 组件挂载时获取数据
onMounted(() => {
  console.log('组件挂载，开始获取数据...')
  console.log('使用的客户端基础URL:', r3.defaults.baseURL)
  fetchVerificationList()
  fetchSupplierList()
})
</script>

<style scoped>
.verification-list {
  padding: 0;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-card {
  margin-bottom: 16px;
}

.search-form {
  margin: 0;
}

.action-card {
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

/* 卡片样式 */
:deep(.el-card) {
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 20px;
}

/* 开关样式 */
:deep(.el-switch) {
  --el-switch-on-color: #409eff;
}

/* 新增对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 8px 8px 0 0;
  padding: 20px 24px;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #ebeef5;
  background-color: #fafafa;
  border-radius: 0 0 8px 8px;
}

/* 表单样式 */
.verification-form {
  padding: 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 4px;
}

:deep(.el-textarea__inner) {
  border-radius: 4px;
}

:deep(.el-radio-group) {
  display: flex;
  gap: 16px;
}

:deep(.el-radio) {
  margin-right: 0;
}

/* 对话框按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.dialog-footer .el-button) {
  border-radius: 4px;
  padding: 8px 20px;
}

/* 详情页样式 */
.detail-container {
  max-height: 600px;
  overflow-y: auto;
}

.detail-card {
  margin-bottom: 16px;
}

.detail-card:last-child {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  min-height: 32px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-label {
  font-weight: 500;
  color: #606266;
  min-width: 120px;
  margin-right: 12px;
}

.detail-value {
  color: #303133;
  flex: 1;
  word-break: break-all;
}

/* 详情页标签样式 */
:deep(.detail-card .el-tag) {
  font-size: 12px;
  padding: 4px 8px;
}


/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 8px 8px 0 0;
  padding: 20px 24px;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #ebeef5;
  background-color: #fafafa;
  border-radius: 0 0 8px 8px;
}

/* 对话框按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.dialog-footer .el-button) {
  border-radius: 4px;
  padding: 8px 20px;
}

/* 供应商选择对话框样式 */
.supplier-search-form {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.supplier-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

/* 供应商表格样式 */
:deep(.supplier-table .el-table) {
  font-size: 14px;
}

:deep(.supplier-table .el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.supplier-table .el-table td) {
  padding: 12px 0;
}

/* 供应商选择行样式 */
:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 单选按钮样式 */
:deep(.el-radio) {
  margin-right: 0;
}

:deep(.el-radio__label) {
  display: none;
}

/* 输入框搜索图标样式 */
:deep(.el-input__suffix) {
  cursor: pointer;
}

:deep(.el-input__suffix:hover) {
  color: #409eff;
}

/* 禁用输入框样式 */
:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #909399;
  cursor: not-allowed;
}

</style>